﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web.UI;
using SBACN.WebSite.Cache;
using SBACN.WebSite.Code;
using SBACN.WebSite.Common;
using SBACN.WebSite.Models;
using SBACN.WebSite.UC;

namespace SBACN.WebSite.Admin.Systems
{
	public partial class RoleList : AdminBasePage
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				this.InitCtrl();
			}
		}

		private void InitCtrl()
		{
			Expression<Func<TB_Role, bool>> f = (p => true);
			Expression<Func<TB_Role, string>> order = (p => p.Name);

			this.rpt_Role.DataSource = DAL.DALHelper.Instance.GetList<TB_Role, string>(f, order, true);
			this.rpt_Role.DataBind();

			var itemList = SystemMapCache.Instance.List.Where(p => (p.IsAdminRight || p.ShowInMap) && p.Status).ToList();
			var fullItemList = new List<TB_SystemMap>();
			foreach (var item in itemList)
			{
				IList<TB_SystemMap> parentList = SystemMapCache.Instance.GetParent(item.Code);
				foreach (var parent in parentList)
				{
					if (!fullItemList.Contains(parent))
					{
						fullItemList.Add(parent);
					}
				}
			}

			this.td_RightList.InnerHtml += "<div style='max-height:330px; overflow-x:hidden;overflow-y:auto;'>";
			foreach (var item in fullItemList.OrderBy(p => p.Code.Substring(0, (p.Code.Length - (p.Code.Length > 4 ? 4 : 1)))).ThenBy(p => p.SortIndex))
			{
				if(item.Code.Length == 4)
				{
					this.td_RightList.InnerHtml += InitRightTable(item, fullItemList, 1);
				}
			}
			this.td_RightList.InnerHtml += "</div>";
			AdminMenu menu = this.Master.FindControl("AdminMenu1") as AdminMenu;
			if (menu != null)
			{
				menu.InitCtrl();
			}
		}

		private string InitRightTable(TB_SystemMap map, IList<TB_SystemMap> rightList,int columns)
		{
			StringBuilder sb = new StringBuilder();
			if (map.Code.Length == 4 && rightList.Where(p => p.Code.StartsWith(map.Code) && p.Code != map.Code).Count() > 0)
			{
				IList<TB_SystemMap> childList = rightList.Where(p => p.Code.StartsWith(map.Code) && p.Code.Length == (map.Code.Length + 4)).ToList();
				sb.Append("<div class='rightTop' style='cursor:pointer;width:100%; height:22px; margin-top:2px; background:#f4f4f4 url(" + AdminPath + "images/right_icon.gif) no-repeat left 40%; padding:3px 0 0 5px; margin-top:2px; padding:3px 0 0 25px;' title='" + map.Name + "'>");
				sb.Append(map.Name);
				sb.Append("</div>");
				sb.Append("<div class='rightChild'>");
				foreach (var item in childList)
				{
					sb.Append(InitRightTable(item, rightList, (childList.Count > 4 ? 4 : childList.Count)));
				}
				sb.Append("</div>");
			}

			if (map.Code.Length == 8)
			{
				if (rightList.Where(p => p.Code.StartsWith(map.Code) && p.Code != map.Code).Count() > 0)
				{
					IList<TB_SystemMap> childList = rightList.Where(p => p.Code.StartsWith(map.Code) && p.Code.Length == (map.Code.Length + 4)).ToList();
					sb.Append("<div class='rightChildMain' style='text-indent:1em;width:100%;float:left; margin-top:2px; height:22px; background:#f6f6f6;padding:5px 0 0 5px;' title='" + map.Name + "'>");
					sb.Append(map.Name);
					sb.Append("</div>");
					//sb.Append("<div class='rightGrandChild'>");
					foreach (var item in childList)
					{
						sb.Append(InitRightTable(item, rightList, (childList.Count > 4 ? 4 : childList.Count)));
					}
					//sb.Append("</div>");
				}
				else
				{
					sb.Append("<div style='text-indent:1em;float:left; width:" + ((100 / columns) - 1) + "%;white-space:nowarp;height:20px;border:1px solid #f4f4f4;'>" + map.Name.CutTo(6, 5) + ":<input name='" + map.Code + "' type='radio' id='rb_R_" + map.Code + "' value='0' /><label for='rb_R_" + map.Code + "'>读</label><input name='" + map.Code + "' type='radio' id='rb_W_" + map.Code + "' value='1' /><label for='rb_W_" + map.Code + "'>写</label><input name='" + map.Code + "' type='radio' id='rb_N_" + map.Code + "' value='' /><label for='rb_N_" + map.Code + "'>拒绝</label></div>");
				}
			}
			
			if (map.Code.Length == 12)
			{
				sb.Append("<div style='text-indent:2em;float:left; width:" + ((100 / columns) - 1) + "%;white-space:nowarp;height:20px;border:1px solid #f4f4f4;'>" + map.Name.CutTo(5, 4) + ":<input name='" + map.Code + "' type='radio' id='rb_R_" + map.Code + "' value='0' /><label for='rb_R_" + map.Code + "'>读</label><input name='" + map.Code + "' type='radio' id='rb_W_" + map.Code + "' value='1' /><label for='rb_W_" + map.Code + "'>写</label><input name='" + map.Code + "' type='radio' id='rb_N_" + map.Code + "' value='' /><label for='rb_N_" + map.Code + "'>拒绝</label></div>");
			}
			return sb.ToString();
		}

		protected void btn_Create_Click(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(this.txt_Name.Text))
			{
				this.lbl_Msg.Text = "角色名称不能为空!";
			}
			else
			{
				int id = 0;
				if (!string.IsNullOrWhiteSpace(this.hid_RoleID.Value) && int.TryParse(this.hid_RoleID.Value, out id))//Eidt
				{
					TB_Role role = RoleCache.Instance.CacheList.Where(p => p.ID == id).FirstOrDefault();
					if (role != null)
					{
						role.Name = txt_Name.Text.Trim();
						role.Description = txt_Memo.Text.Trim();
						role.Status = rbl_Status.SelectedValue == "1";
						DAL.DALHelper.Instance.UpdateWithTransaction(role, "ID");
						DAL.DALHelper.Instance.SaveChanges();
						id = role.ID;
					}
				}
				else//CreateNew
				{
					TB_Role role = DAL.DALHelper.Instance.Create<TB_Role>();

					role.Name = txt_Name.Text.Trim();
					role.Status = rbl_Status.SelectedValue == "1";
					role.Description = txt_Memo.Text.Trim();
					role.Editable = true;

					DAL.DALHelper.Instance.Add(role);
					DAL.DALHelper.Instance.SaveChanges();
					id = role.ID;
				}

				Expression<Func<TB_RoleRightRelation, bool>> f = (p => p.RoleID == id);
				DAL.DALHelper.Instance.DeleteWithTransaction(f);
				var relateList = this.hid_RightList.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
				foreach (string s in relateList)
				{
					var rightType = s.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
					if (rightType.Length == 2)
					{
						TB_RoleRightRelation r = DAL.DALHelper.Instance.Create<TB_RoleRightRelation>();
						r.RoleID = id;
						r.Code = rightType[0];
						r.Type = rightType[1] == "1";
						DAL.DALHelper.Instance.Add(r);
					}
				}
				DAL.DALHelper.Instance.SaveChanges();
				RoleCache.Instance.Clear();
				RoleRightCache.Instance.Clear();
				UserRightCache.Instance.Clear();
			}
			InitCtrl();
		}

		protected void btn_Delete_Click(object sender, EventArgs e)
		{
			int id = 0;
			if (!string.IsNullOrWhiteSpace(this.hid_RoleID.Value) && int.TryParse(this.hid_RoleID.Value, out id))
			{
				//TB_Role role = DAL.DALHelper.Instance.GetObject<TB_Role>("ID", id);
				TB_Role role = RoleCache.Instance.CacheList.Where(p => p.ID == id).FirstOrDefault();
				if(role != null)
				{
					role.Status = !role.Status;
					DAL.DALHelper.Instance.Update<TB_Role>(role);
					DAL.DALHelper.Instance.SaveChanges();
					RoleCache.Instance.Clear();
					RoleRightCache.Instance.Clear();
					UserRightCache.Instance.Clear();
				}
				//DAL.DALHelper.Instance.DeleteWithTransaction<TB_AdminRight>("ID", id);
			}
			InitCtrl();
		}
	}
}